﻿//-----------------------------------------------------------------------
// <copyright file="KeyIDMakerHalder.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: KeyIDMakerHalder.cs
// * history : created by qinchaoyue 2017-10-24 01:30:40
// </copyright>
//-----------------------------------------------------------------------
    
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Slwy.Utility.ConfigurManager;

namespace Slwy.KeyIDMaker
{
    /// <summary>
    /// KeyID生成
    /// </summary>
    public class KeyIDMakerHalder
    {
        /// <summary>
        /// 锁对象
        /// </summary>
        private static object lockObj = new object();

        /// <summary>
        /// 保存最近50个KeyID队列
        /// </summary>
        private static Queue<string> keyIDQueue = new Queue<string>();

        /// <summary>
        /// 队列最大数目
        /// </summary>
        private static int queueCount = 50;

        /// <summary>
        /// 生成KeyID
        /// </summary>
        /// <param name="bizType">业务线</param>
        /// <returns>KeyID</returns>
        public static string NewKeyID(BizType bizType)
        {
            var keyIdMaker = new ConfigurHandler().GetAppOptions<MKeyIdMaker>("KeyIDMarkSetting");
            Monitor.Enter(lockObj);
            string resKeyId;
            StringBuilder sb = new StringBuilder();

            // 当前时间
            sb.Append(DateTime.Now.ToString("yyMMddHHmmssfff"));

            // 产品线、业务线
            sb.Append((int)bizType);

            // 机器码（读文件）
            sb.Append(keyIdMaker.MachineNo);

            // 随机数
            sb.Append(new Random().Next(10000000).ToString("000000"));

            ////队列中包含就重新生成
            if (keyIDQueue.Contains(sb.ToString()))
            {
                resKeyId = KeyIDMakerHalder.NewKeyID(bizType);
            }
            else
            {
                resKeyId = sb.ToString();
            }

            keyIDQueue.Enqueue(resKeyId);

            if (keyIDQueue.Count > queueCount)
            {
                keyIDQueue.Dequeue();
            }

            Monitor.Exit(lockObj);

            return resKeyId;
        }
    }
}
